package com.ilvyou.api.service;

import com.ilvyou.core.base.BaseService;
import com.ilvyou.core.dao.Criteria;
import com.ilvyou.core.dao.Dao;
import com.ilvyou.data.lvzan.AppUserEntity;
import com.ilvyou.data.lvzan.BaseSequenceEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by GuanYuCai on 2016/9/8 0008.
 */
@Service
public class ZanService extends BaseService {

    @Resource(name = "zanDao")
    private Dao zanDao;

    @Override
    protected Dao getDao() {
        return zanDao;
    }

    public String getSequenceName(String table, String column) throws Exception{

        //查询对应的表格的序列表信息
        BaseSequenceEntity baseSequence = zanDao.get(BaseSequenceEntity.class,
                new Criteria().add("tablename=? and columnname=?", table, column));
        String name = getCodeValue(baseSequence);

        //最后序列自增
        baseSequence.setLastsequence(baseSequence.getLastsequence() + 1);
        zanDao.update(baseSequence);
        return name;
    }

    public AppUserEntity getZanUserByAccount(String account) throws Exception {
        return zanDao.get(AppUserEntity.class,
                new Criteria().add("loginname=?", account));
    }

    private String getCodeValue(BaseSequenceEntity seq){

        // firstLets是code开头的字符 如订单的S,bpp_user的SK
        String firstLets  = seq.getFormats();
        long nowNum = seq.getLastsequence(); // 获取序列的现有值的int值
        int dataLength = seq.getDatalength(); // code长度

        String formart;
        if(firstLets.equalsIgnoreCase("CRS") || firstLets.equalsIgnoreCase("STR")){
            formart = "%05d";
        }else{
            formart = "%0" + (dataLength - firstLets.length()) +"d";
        }
        return firstLets + String.format(formart, nowNum);
    }
}
